package com.maoning.gulimallssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * @Author : 猫宁
 * @Date: 2021/10/11
 */
@Controller
public class HelloController {
    @Value("${sso.server.url}")
    String ssoServerUrl;

    /**
     * 无需登陆就可访问
     * @return
     */
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    /**
     *
     * @param model
     * @param session
     * @param token sso登陆成功以后,带过来的
     * @return
     */
    @RequestMapping("/boss")
    public String employees(Model model,
                            HttpSession session,
                            @RequestParam(value = "token",required = false) String token){
        //先看一下请求来的时候带没带token,如果带了,说明是从sso登陆成功来的,直接给通过
        if(!StringUtils.isEmpty(token)){
            final RestTemplate restTemplate = new RestTemplate();
            final ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            final String body = forEntity.getBody();
            session.setAttribute("loginUser", body);
        }

        //如果没带token,说明是浏览器过来的,那就尝试拿本地session,或者去sso走流程
        final Object loginUser = session.getAttribute("loginUser");

        if(loginUser == null){
            //如果获取为null说明没有登陆,跳转到登陆服务器
            //返回的时候告诉登陆服务器,自己的url是多少,让登陆服务器可以跳回来
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
        }else {
            final ArrayList<String> list = new ArrayList<>();
            list.add("张三");
            list.add("李四");
            model.addAttribute("emps", list);
        }


        return "list";
    }
}
